package edu.xidian.forum.validation;

import edu.xidian.forum.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

@RestControllerAdvice
public class GlobalValidationExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalValidationExceptionHandler.class);

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({BindException.class, ValidationException.class})
    public Result<Void> handleValidationException(Exception e) {
        if (e instanceof BindException) {
            FieldError fieldError = ((BindException) e).getFieldError();
            if (fieldError != null) {
                return Result.badRequest(fieldError.getDefaultMessage());
            }
        } else if (e instanceof ConstraintViolationException) {
            String message = e.getMessage();
            if (message != null) {
                int lastIndex = message.lastIndexOf(':');
                if (lastIndex >= 0) {
                    Result.badRequest(message.substring(lastIndex + 1).trim());
                }
            }
        }
        LOGGER.warn("The validation exception without message.", e);
        return Result.badRequest();
    }
}
